package com.ygswglxt.attendance.controller;

import com.ygswglxt.attendance.entity.AttendanceRecord;
import com.ygswglxt.attendance.entity.AttendanceRule;
import com.ygswglxt.attendance.entity.AttendanceSupplement;
import com.ygswglxt.attendance.service.AttendanceService;
import com.ygswglxt.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/attendance")
public class AttendanceController {
    
    @Autowired
    private AttendanceService attendanceService;
    
    @PostMapping("/checkin")
    public Result<String> checkIn(HttpServletRequest request) {
        Long userId = Long.parseLong(request.getHeader("userId"));
        return attendanceService.checkIn(userId);
    }
    
    @PostMapping("/checkout")
    public Result<String> checkOut(HttpServletRequest request) {
        Long userId = Long.parseLong(request.getHeader("userId"));
        return attendanceService.checkOut(userId);
    }
    
    @PostMapping("/overtime")
    public Result<String> overtime(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String userIdStr = request.getHeader("userId");
            if (userIdStr == null || userIdStr.isEmpty()) {
                return Result.error(401, "用户未登录");
            }
            
            Long userId;
            try {
                userId = Long.parseLong(userIdStr);
            } catch (NumberFormatException e) {
                return Result.error(400, "用户ID格式错误");
            }
            
            // 处理hours参数，支持多种数字类型
            Integer hours = 1;
            if (params.get("hours") != null) {
                Object hoursObj = params.get("hours");
                if (hoursObj instanceof Integer) {
                    hours = (Integer) hoursObj;
                } else if (hoursObj instanceof Number) {
                    hours = ((Number) hoursObj).intValue();
                } else {
                    try {
                        hours = Integer.parseInt(hoursObj.toString());
                    } catch (NumberFormatException e) {
                        hours = 1;
                    }
                }
            }
            
            String date = params.get("date") != null ? params.get("date").toString() : null;
            String reason = params.get("reason") != null ? params.get("reason").toString() : null;
            
            return attendanceService.overtime(userId, hours, date, reason);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("提交失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/my")
    public Result<List<AttendanceRecord>> getMyRecords(HttpServletRequest request) {
        Long userId = Long.parseLong(request.getHeader("userId"));
        return attendanceService.getMyRecords(userId);
    }
    
    @GetMapping("/overtime/my")
    public Result<List<AttendanceRecord>> getMyOvertimeRecords(HttpServletRequest request) {
        Long userId = Long.parseLong(request.getHeader("userId"));
        return attendanceService.getMyOvertimeRecords(userId);
    }
    
    @GetMapping("/all")
    public Result<List<AttendanceRecord>> getAllRecords(HttpServletRequest request) {
        String role = request.getHeader("role");
        if (!"MANAGER".equals(role) && !"HR".equals(role)) {
            return Result.error(403, "无权限访问");
        }
        return attendanceService.getAllRecords();
    }
    
    // 获取待审批的加班申请
    @GetMapping("/overtime/pending")
    public Result<List<AttendanceRecord>> getPendingOvertime(HttpServletRequest request) {
        String role = request.getHeader("role");
        if (!"MANAGER".equals(role)) {
            return Result.error(403, "无权限访问");
        }
        return attendanceService.getPendingOvertime();
    }
    
    // 审批加班
    @PostMapping("/overtime/approve")
    public Result<String> approveOvertime(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        String role = request.getHeader("role");
        if (!"MANAGER".equals(role)) {
            return Result.error(403, "无权限访问");
        }
        Long recordId = Long.parseLong(params.get("recordId").toString());
        Long approverId = Long.parseLong(request.getHeader("userId"));
        String status = params.get("status").toString();
        return attendanceService.approveOvertime(recordId, approverId, status);
    }
    
    // 查看下属考勤
    @GetMapping("/subordinate")
    public Result<List<AttendanceRecord>> getSubordinateRecords(HttpServletRequest request) {
        String role = request.getHeader("role");
        if (!"MANAGER".equals(role)) {
            return Result.error(403, "无权限访问");
        }
        Long managerId = Long.parseLong(request.getHeader("userId"));
        return attendanceService.getSubordinateRecords(managerId);
    }
    
    // 导出团队考勤记录
    @GetMapping("/subordinate/export")
    public void exportSubordinateRecords(
            HttpServletRequest request,
            HttpServletResponse response) {
        try {
            String role = request.getHeader("role");
            if (!"MANAGER".equals(role)) {
                response.setStatus(403);
                return;
            }
            Long managerId = Long.parseLong(request.getHeader("userId"));
            attendanceService.exportSubordinateRecords(response, managerId);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(500);
        }
    }
    
    // 考勤统计（HR使用）
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getAttendanceStatistics(@RequestParam(required = false) String month, HttpServletRequest request) {
        String role = request.getHeader("role");
        if (role == null || !"HR".equals(role)) {
            return Result.error(403, "无权限访问，仅HR角色可以查看考勤统计");
        }
        try {
            return attendanceService.getAttendanceStatistics(month);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取统计数据失败: " + e.getMessage());
        }
    }
    
    // 获取异常考勤记录（支持更多筛选条件）
    @GetMapping("/exception")
    public Result<List<AttendanceRecord>> getExceptionRecords(
            @RequestParam(required = false) String month,
            @RequestParam(required = false) String exceptionType,
            @RequestParam(required = false) String exceptionStatus,
            HttpServletRequest request) {
        try {
            String userIdStr = request.getHeader("userId");
            String role = request.getHeader("role");
            Long userId = null;
            
            // 只有员工查看自己的异常记录，HR和经理可以查看所有
            if (!"HR".equals(role) && !"MANAGER".equals(role)) {
                userId = Long.parseLong(userIdStr);
            }
            
            return attendanceService.getExceptionRecords(userId, month, exceptionType, exceptionStatus);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取异常考勤记录失败: " + e.getMessage());
        }
    }
    
    // 获取异常统计信息
    @GetMapping("/exception/statistics")
    public Result<Map<String, Object>> getExceptionStatistics(
            @RequestParam(required = false) String month,
            HttpServletRequest request) {
        try {
            String role = request.getHeader("role");
            // HR和经理可以查看统计，员工只能查看自己的
            if (role == null || (!"HR".equals(role) && !"MANAGER".equals(role))) {
                return Result.error(403, "无权限访问");
            }
            return attendanceService.getExceptionStatistics(month);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取异常统计失败: " + e.getMessage());
        }
    }
    
    // 处理异常考勤记录
    @PostMapping("/exception/handle")
    public Result<String> handleException(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String role = request.getHeader("role");
            if (!"HR".equals(role) && !"MANAGER".equals(role)) {
                return Result.error(403, "无权限访问");
            }
            
            Long recordId = Long.parseLong(params.get("recordId").toString());
            Long handlerId = Long.parseLong(request.getHeader("userId"));
            String status = params.get("status").toString();
            String remark = params.get("remark") != null ? params.get("remark").toString() : "";
            
            return attendanceService.handleException(recordId, handlerId, status, remark);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("处理失败: " + e.getMessage());
        }
    }
    
    // 申请补卡
    @PostMapping("/supplement")
    public Result<String> applySupplement(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            Long userId = Long.parseLong(request.getHeader("userId"));
            String date = params.get("date").toString();
            String type = params.get("type").toString(); // CHECK_IN, CHECK_OUT
            String time = params.get("time").toString(); // HH:mm:ss
            String reason = params.get("reason") != null ? params.get("reason").toString() : "";
            
            return attendanceService.applySupplement(userId, date, type, time, reason);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("提交补卡申请失败: " + e.getMessage());
        }
    }
    
    // 获取我的补卡申请
    @GetMapping("/supplement/my")
    public Result<List<AttendanceSupplement>> getMySupplements(HttpServletRequest request) {
        try {
            Long userId = Long.parseLong(request.getHeader("userId"));
            return attendanceService.getMySupplements(userId);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取补卡申请失败: " + e.getMessage());
        }
    }
    
    // 获取待审批的补卡申请（经理/HR）
    @GetMapping("/supplement/pending")
    public Result<List<AttendanceSupplement>> getPendingSupplements(HttpServletRequest request) {
        String role = request.getHeader("role");
        if (!"MANAGER".equals(role) && !"HR".equals(role)) {
            return Result.error(403, "无权限访问");
        }
        return attendanceService.getPendingSupplements();
    }
    
    // 审批补卡申请
    @PostMapping("/supplement/approve")
    public Result<String> approveSupplement(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String role = request.getHeader("role");
            if (!"MANAGER".equals(role) && !"HR".equals(role)) {
                return Result.error(403, "无权限访问");
            }
            
            Long supplementId = Long.parseLong(params.get("supplementId").toString());
            Long approverId = Long.parseLong(request.getHeader("userId"));
            String status = params.get("status").toString();
            String remark = params.get("remark") != null ? params.get("remark").toString() : "";
            
            return attendanceService.approveSupplement(supplementId, approverId, status, remark);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("审批失败: " + e.getMessage());
        }
    }
    
    // 获取考勤规则列表（HR）
    @GetMapping("/rule")
    public Result<List<AttendanceRule>> getAttendanceRules(HttpServletRequest request) {
        String role = request.getHeader("role");
        if (!"HR".equals(role) && !"OTHER".equals(role)) {
            return Result.error(403, "无权限访问");
        }
        return attendanceService.getAttendanceRules();
    }
    
    // 保存考勤规则（HR）
    @PostMapping("/rule")
    public Result<String> saveAttendanceRule(@RequestBody AttendanceRule rule, HttpServletRequest request) {
        String role = request.getHeader("role");
        if (!"HR".equals(role) && !"OTHER".equals(role)) {
            return Result.error(403, "无权限访问");
        }
        return attendanceService.saveAttendanceRule(rule);
    }
    
    // 导出考勤统计（HR）
    @GetMapping("/statistics/export")
    public void exportAttendanceStatistics(
            @RequestParam(required = false) String month,
            HttpServletRequest request,
            HttpServletResponse response) {
        try {
            String role = request.getHeader("role");
            if (role == null || !"HR".equals(role)) {
                response.setStatus(403);
                return;
            }
            attendanceService.exportAttendanceStatistics(response, month);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(500);
        }
    }
    
    // 导出异常考勤记录
    @GetMapping("/exception/export")
    public void exportExceptionRecords(
            @RequestParam(required = false) String month,
            @RequestParam(required = false) String exceptionType,
            @RequestParam(required = false) String exceptionStatus,
            HttpServletRequest request,
            HttpServletResponse response) {
        try {
            String userIdStr = request.getHeader("userId");
            String role = request.getHeader("role");
            Long userId = null;
            
            // 只有员工查看自己的异常记录，HR和经理可以查看所有
            if (!"HR".equals(role) && !"MANAGER".equals(role)) {
                userId = Long.parseLong(userIdStr);
            }
            
            attendanceService.exportExceptionRecords(response, userId, month, exceptionType, exceptionStatus);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(500);
        }
    }
}

